# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import json
from django.shortcuts import render
from api_application.base_api import BaseApi
from django.http import JsonResponse
from .models import NameList

# 开发框架中通过中间件默认是需要登录态的，如有不需要登录的，可添加装饰器login_exempt
# 装饰器引入 from blueapps.account.decorators import login_exempt

"""
作业平台接口
https://bk.tencent.com/docs/document/6.0/130/13273
"""

bk_cmdb_api = BaseApi("CMDB_API_URL")
bk_job_api = BaseApi("JOB_API_URL")


def job_list(request):
    """
    作业模板
    """
    return render(request, "home_application/job_list.html")


def implementation_program(request):
    """
    执行方案
    """
    return render(request, "home_application/implementation_program.html")


def scheduled_task(request):
    """
    定时任务
    """
    return render(request, "home_application/scheduled_task.html")


def execution_history(request):
    """
    执行历史
    """
    return render(request, "home_application/execution_history.html")


def search_business(request):
    """
    # 查询业务
    """
    bizs = bk_cmdb_api.requests("POST", "search_business")
    name_list = NameList.objects.filter().first().name_list
    black_bizs = name_list.get("black_bizs")
    if not black_bizs: black_bizs = [2, 3, 11, 12, 13]

    biz_infos = bizs["data"]["info"] if bizs.get("result", False) else []
    bizs = [item for item in biz_infos if (item['bk_biz_id'] not in black_bizs)]
    return JsonResponse({"bizs": bizs})


def search_biz_inst_topo(request):
    # 查询业务实例拓扑
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    resp = {}
    if bk_biz_id:
        # 查询业务实例拓扑
        resp = bk_cmdb_api.requests("POST", "search_biz_inst_topo", {"bk_biz_id": bk_biz_id})
    return JsonResponse(resp)


def get_job_plan_list(request):
    # 查询执行方案列表
    """
    {
        "bk_biz_id": 1,
        "job_template_id": 1,  # 作业模版 ID
        "creator": "admin", # 作业执行方案创建人帐号
        "name": "test",   # 作业执行方案名称，模糊匹配
        "create_time_start": 1546272000000,   # 创建起始时间，Unix 时间戳
        "create_time_end": 1577807999999,   # 创建结束时间，Unix 时间戳
        "last_modify_user": "admin",   # 作业执行方案修改人帐号
        "last_modify_time_start": 1546272000000,   # 最后修改起始时间，Unix 时间戳
        "last_modify_time_end": 1577807999999,   # 最后修改结束时间，Unix 时间戳
        "start": 0,   # 	默认0表示从第1条记录开始返回
        "length": 1000   # 单次返回最大记录数，最大1000，不传默认为20
    }
    """
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    resp = {}
    if bk_biz_id:
        resp = bk_job_api.requests("POST", "get_job_plan_list", {
            "bk_biz_id": bk_biz_id,
            "start": 0,  # 默认0表示从第1条记录开始返回
            "length": 1000  # 单次返回最大记录数，最大1000，不传默认为20
        })
        # resp = {"data": resp["data"]["data"], "total": resp["data"]["total"]}
    return JsonResponse(resp)


def execute_job_plan(request):
    """
    执行作业执行方案
    https://bkapi.paas-edu.bktencent.com/api/c/compapi/v2/jobv3/execute_job_plan/
    """
    resp = bk_job_api.requests("POST", "execute_job_plan", {
        "bk_biz_id": 1,
        "job_plan_id": 100,
        "global_var_list": [
            {
                "id": 436,
                "server": {
                    "dynamic_group_list": [
                        {
                            "id": "blo8gojho0skft7pr5q0"
                        }
                    ],
                    "ip_list": [
                        {
                            "bk_cloud_id": 0,
                            "ip": "10.0.0.1"
                        },
                        {
                            "bk_cloud_id": 0,
                            "ip": "10.0.0.2"
                        }
                    ],
                    "topo_node_list": [
                        {
                            "id": 1000,
                            "node_type": "module"
                        }
                    ]
                }
            },
            {
                "name": "param_name",
                "value": "param_value"
            }
        ]})
    return JsonResponse(resp)


def get_job_plan_detail(request):
    # 查询执行方案详情
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    job_plan_id = params.get("job_plan_id", None)

    resp = bk_job_api.requests("GET", "get_job_plan_detail", {
        "bk_biz_id": bk_biz_id,
        "job_plan_id": job_plan_id
    })
    return JsonResponse(resp)


def get_cron_list(request):
    """
    # 查询业务下定时作业信息
    {
        "bk_biz_id": 2,
        "name": "test",  #  否	定时作业名称
        "id": 1000031,  # 定时任务 ID，如果存在则忽略其他筛选条件，只查询这个指定的作业信息
        "status": 1,   # 否	定时作业状态：1.已启动、2.已暂停
        "creator": "admin",
        "create_time_start": 1601371525,
        "create_time_end": 1617285956,
        "last_modify_user": "admin",
        "last_modify_time_start": 1601371525,
        "last_modify_time_end": 1617286227,
        "start": 0,
        "length": 1
    }
    """
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    resp = bk_job_api.requests("POST", "get_cron_list", {
        "bk_biz_id": bk_biz_id,
        "start": 0,
        "length": 1000
    })
    return JsonResponse(resp)


def get_cron_detail(request):
    # 查询定时作业详情
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    id = params.get("id", None)
    resp = bk_job_api.requests("POST", "get_cron_detail", {
        "bk_biz_id": bk_biz_id,  # 业务ID
        "id": id  # 定时任务ID
    })
    return JsonResponse(resp)


def get_job_instance_list(request):
    """
    # 查询作业实例列表(执行历史)
    {
        "bk_biz_id": 1,
        "type": 0,   # 否	任务类型。0 - 作业执行，1 - 脚本执行，2 - 文件分发
        "launch_mode": 1,  # 否 执行方式。1 - 页面执行，2 - API调用，3 - 定时执行
        "status": 3, 	# 否	任务状态。1 - 等待执行，2 - 正在执行，3 - 执行成功，4 - 执行失败，7 - 等待确认，9 - 状态异常，10 - 强制终止中，11 - 强制终止成功，13 - 确认终止
        "operator": "admin",  # 否	执行人，精准匹配
        "name": "test",   # 否	任务名称，模糊匹配
        "create_time_start": 1546272000000,   # 是	创建起始时间，Unix 时间戳，单位毫秒
        "create_time_end": 1577807999999, # 是	创建结束时间，Unix 时间戳，单位毫秒
        "start": 0,
        "length": 1000
    }
    """
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    create_time_start = params.get("create_time_start", None)
    create_time_end = params.get("create_time_end", None)
    start = params.get("start", 0)
    length = params.get("length", 30)
    resp = bk_job_api.requests("POST", "get_job_instance_list", {
        "bk_biz_id": bk_biz_id,
        "create_time_start": create_time_start,
        "create_time_end": create_time_end,
        "start": start,
        "length": length
    })
    return JsonResponse(resp)


def get_job_template_list(request):
    """
    查询作业模版列表
    {
        "bk_biz_id": 1,  # 是
        "creator": "admin",
        "name": "test",
        "create_time_start": 1546272000000,
        "create_time_end": 1577807999999,
        "last_modify_user": "admin",
        "last_modify_time_start": 1546272000000,
        "last_modify_time_end": 1577807999999,
        "start": 0,
        "length": 20
    }
    """
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    start = params.get("start", 0)
    length = params.get("length", 30)
    resp = bk_job_api.requests("POST", "get_job_template_list", {
        "bk_biz_id": bk_biz_id,
        "start": start,
        "length": length
    })
    return JsonResponse(resp)


# 获取错误日志
def batch_get_job_instance_ip_log(request):
    # 根据ip列表批量查询作业执行日志
    data = {
        "bk_biz_id": 1,
        "job_instance_id": 100,  # 作业实例ID
        "step_instance_id": 200,  # 步骤实例ID
        "ip_list": [
            {
                "bk_cloud_id": 0,  # 云区域ID
                "ip": "10.0.0.1"  # IP地址
            },
            {
                "bk_cloud_id": 0,
                "ip": "10.0.0.2"
            }
        ]
    }
    res = bk_job_api.requests("POST", "batch_get_job_instance_ip_log", data)
    return JsonResponse(res)


def get_job_instance_status(request):
    # 根据作业实例ID查询作业执行状态
    return


def get_job_instance_ip_log(request):
    # 根据作业实例ID查询作业执行日志
    bk_job_api.requests("GET", "get_job_instance_ip_log", {
        "bk_biz_id": 1,
        "job_instance_id": 50,  # 作业实例ID
        "step_instance_id": 100,  # 步骤实例ID
        "bk_cloud_id": 0,  # 目标服务器云区域ID
        "ip": "10.0.0.1"  # 目标服务器IP
    })
    return


# 配置作业平台执行流程， 实现一次游戏客户端的发布，包括文件上传，脚本执行等元素
def fast_execute_script(request):
    # 快速执行脚本
    bk_job_api.requests("POST", "fast_execute_script", {
        "bk_biz_id": 1,  # 业务ID
        "account_id": 1000,  # 执行账号ID。与account_alias必须存在一个。当同时存在account_alias和account_id时，account_id优先。

        "script_version_id": 1,  # 脚本版本ID。当script_version_id不为空的时候，使用script_version_id对应的脚本版本
        "script_content": "ZWNobyAkMQ==",  # 脚本内容Base64。如果不存在script_version_id和script_id,那么使用script_content。优先级：script_version_id>script_id>script_content
        "script_param": "aGVsbG8=",  # 脚本参数Base64。注意：如果有多个参数，比如"param1 param2"这种，需要对"param1 param2"整体进行base64编码，而不是对每个参数进行base64编码再拼接起来
        "timeout": 1000,  # 脚本执行超时时间，秒。默认7200，取值范围1-86400

        "is_param_sensitive": 0,  # 敏感参数将会在执行详情页面上隐藏, 0:不是（默认），1:是
        "script_language": 1,  # 脚本语言：1 - shell, 2 - bat, 3 - perl, 4 - python, 5 - powershell。当使用script_content传入自定义脚本的时候，需要指定script_language
        "target_server": {  # 目标服务器
            "dynamic_group_list": [
                {
                    "id": "blo8gojho0skft7pr5q0"  # CMDB动态分组ID
                }
            ],
            "ip_list": [  # 静态 IP 列表
                {
                    "bk_cloud_id": 0,  # 云区域ID
                    "ip": "10.0.0.1"
                },
                {
                    "bk_cloud_id": 0,
                    "ip": "10.0.0.2"
                }
            ],
            "topo_node_list": [
                {
                    "id": 1000,  # 动态topo节点ID，对应CMDB API 中的 bk_inst_id
                    "node_type": "module"  # 动态topo节点类型，对应CMDB API 中的 bk_obj_id,比如"module","set"
                }
            ]
        },
        "callback_url": ""  # 回调URL，当任务执行完成后，JOB会调用该URL告知任务执行结果。回调协议参考callback_protocol组件文档
    })
    return


def fast_execute_sql(request):
    # 快速执行SQL
    bk_job_api.requests("POST", "fast_execute_sql", {
        "bk_biz_id": 1,
        "script_version_id": 1,
        "timeout": 1000,
        "db_account_id": 32,
        "target_server": {
            "dynamic_group_list": [
                {
                    "id": "blo8gojho0skft7pr5q0"
                }
            ],
            "ip_list": [
                {
                    "bk_cloud_id": 0,
                    "ip": "10.0.0.1"
                },
                {
                    "bk_cloud_id": 0,
                    "ip": "10.0.0.2"
                }
            ],
            "topo_node_list": [
                {
                    "id": 1000,
                    "node_type": "module"
                }
            ]
        }
    })
    return


def fast_transfer_file(request):
    # 快速分发文件
    bk_job_api.requests("POST", "fast_transfer_file", {
        "bk_biz_id": 1,
        "file_target_path": "/tmp/",
        "transfer_mode": 1,
        "file_source_list": [
            {
                "file_list": [
                    "/tmp/REGEX:[a-z]*.txt"
                ],
                "account": {
                    "id": 100
                },
                "server": {
                    "dynamic_group_list": [
                        {
                            "id": "blo8gojho0skft7pr5q0"
                        },
                        {
                            "id": "blo8gojho0sabc7priuy"
                        }
                    ],
                    "ip_list": [
                        {
                            "bk_cloud_id": 0,
                            "ip": "10.0.0.1"
                        },
                        {
                            "bk_cloud_id": 0,
                            "ip": "10.0.0.2"
                        }
                    ],
                    "topo_node_list": [
                        {
                            "id": 1000,
                            "node_type": "module"
                        }
                    ]
                },
                "file_type": 1
            },
            {
                "file_list": [
                    "testbucket/test.txt"
                ],
                "file_type": 3,
                "file_source_id": 1
            },
            {
                "file_list": [
                    "testbucket/test2.txt"
                ],
                "file_type": 3,
                "file_source_code": "testInnerCOS"
            }
        ],
        "target_server": {
            "dynamic_group_list": [
                {
                    "id": "blo8gojho0skft7pr5q0"
                },
                {
                    "id": "blo8gojho0sabc7priuy"
                }
            ],
            "ip_list": [
                {
                    "bk_cloud_id": 0,
                    "ip": "10.0.0.1"
                },
                {
                    "bk_cloud_id": 0,
                    "ip": "10.0.0.2"
                }
            ],
            "topo_node_list": [
                {
                    "id": 1000,
                    "node_type": "module"
                }
            ]
        },
        "account_id": 101
    })
    return


def update_cron_status(request):
    # 更新定时作业状态，如启动或暂停
    bk_job_api.requests("POST", "update_cron_status", {
        "bk_biz_id": 1,
        "id": 2,
        "status": 1
    })
    return


def save_cron(request):
    # 新建或保存定时作业
    bk_job_api.requests("POST", "save_cron", {
        "bk_username": "admin",
        "bk_biz_id": 2,
        "execute_time": 0,
        "expression": "0 0/5 * * *",
        "job_plan_id": 1023060,
        "name": "test API",
        "global_var_list": [
            {
                "name": "stringVar",
                "value": "value11112"
            },
            {
                "name": "nsVar",
                "value": "nsvalue11112"
            },
            {
                "name": "secretVar",
                "value": "secretvalue11112"
            },
            {
                "name": "dictVar",
                "value": "([\"var1\"]=1, [\"var2\"]=2)"
            },
            {
                "name": "indexArrVar",
                "value": "(2 3 4)"
            },
            {
                "name": "hostVar",
                "server": {
                    "ip_list": [
                        {
                            "bk_cloud_id": 0,
                            "ip": "10.0.0.1"
                        }
                    ]
                }
            }
        ]
    })
    return


def get_account_list(request):
    """
    查询业务下的执行账号
    """
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    res = bk_job_api.requests("POST", "get_account_list", {"bk_biz_id": bk_biz_id})
    return JsonResponse(res)

# 获取作业执行状态接口
